import 'dart:io';

import 'package:device_info/device_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/widgets/common_dialog.dart';
import 'package:flutter_syt/domain/widgets/custom_dialog.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';

// import 'package:flutter_syt/domain/widgets/common_dialog.dart';
// import 'package:flutter_syt/domain/widgets/custom_dialog.dart';
// import 'package:flutter_syt/generated/l10n.dart';
// import 'package:flutter_syt/theme/theme_color.dart';

class PermissionHelper {
  // {title: , detail: {CAMERA: {zh: 请输入相机授权-中文, en: ssss}, ACCESS_COARSE_LOCATION: {zh: 粗略位置授权-中文, en: testt}, ACCESS_FINE_LOCATION: {zh: 精确位置授权-中文, en: testt2}, WRITE_EXTERNAL_STORAGE: {zh: 存储授权-中文, en: testt4}, RECORD_AUDIO: {zh: 麦克风授权-中文, en: testt5}}}
//CAMERA  ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION  WRITE_EXTERNAL_STORAGE RECORD_AUDIO
  static String? getPermissionTips(String key) {
    if (appContext.permissionData != null &&
        appContext.permissionData!['detail'].keys.toList().contains(key)) {
      var local =
          appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale();
      return appContext.permissionData!['detail'][key]
          [local.contains('zh') ? 'zh' : 'en'];
    }
    return null;
  }

  static Future<bool> checkCameraPermission(BuildContext context) async {
    PermissionStatus pStatus = await Permission.camera.status;
    // DLog(getPermissionTips('CAMERA'));
    if (Platform.isAndroid && pStatus == PermissionStatus.denied) {
      if ((appContext.storage.getString('PermissionCamera') ?? "") != '1') {
        // {title: , detail: {CAMERA: {zh: 请输入相机授权-中文, en: ssss}, ACCESS_COARSE_LOCATION: {zh: 粗略位置授权-中文, en: testt}, ACCESS_FINE_LOCATION: {zh: 精确位置授权-中文, en: testt2}, WRITE_EXTERNAL_STORAGE: {zh: 存储授权-中文, en: testt4}, RECORD_AUDIO: {zh: 麦克风授权-中文, en: testt5}}}
        var iscuees = await PermissionHelper.showTipsPermissionDialog(
            context,
            S.current.permission_tips,
            getPermissionTips('CAMERA') ?? S().NSCameraUsageDescription);
        if (iscuees != true) {
          return false;
        }
      }
    }
    PermissionStatus status = await Permission.camera.request();

    print('Is camera permission granted --> $status');
    var preDenied = appContext.storage.getString('PermissionCamera') ?? "";
    // 完全完毕
    if (status.isGranted || status.isLimited) {
      return true;
    } else {
      if (preDenied == '1') {
        showPermissionDialog(
            context, S.of(context).privacy_setting_camera_toast);
      } else {
        appContext.storage.setString('PermissionCamera', '1');
      }
      return false;
    }
  }

  // static Future<bool> checkMicrophonePermission(BuildContext context) async {
  //   PermissionStatus pStatus = await Permission.microphone.status;
  //   // DLog(camera);
  //   if (Platform.isAndroid && pStatus == PermissionStatus.denied) {
  //     if ((appContext.storage.getString('PermissionMicrophone') ?? "") != '1') {
  //       var iscuees = await PermissionHelper.showTipsPermissionDialog(
  //           context,
  //           S().permission_tips,
  //           getPermissionTips('RECORD_AUDIO') ??
  //               S().NSMicrophoneUsageDescription);
  //       if (iscuees != true) {
  //         return false;
  //       }
  //     }
  //   }
  //
  //   PermissionStatus status = await Permission.microphone.request();
  //   print('Is microphone permission granted --> $status');
  //   var preDenied = appContext.storage.getString('PermissionMicrophone') ?? "";
  //   // 完全完毕
  //   if (status.isGranted || status.isLimited) {
  //     return true;
  //   } else {
  //     if (preDenied == '1') {
  //       showPermissionDialog(
  //           context, S.of(context).privacy_setting_microphone_toast);
  //     } else {
  //       appContext.storage.setString('PermissionMicrophone', '1');
  //     }
  //     return false;
  //   }
  // }

  static Future<bool> checkPhotosPermission(BuildContext context) async {
    AndroidDeviceInfo? deviceData;
    if (Platform.isAndroid) {
      deviceData =  appContext.andriodInfo;//   await DeviceInfoPlugin().androidInfo;
    }

    PermissionStatus pStatus;
    if (Platform.isIOS ||
        (Platform.isAndroid &&
            (int.tryParse(deviceData?.version.release ??'13') ?? 0) >= 13)) {
      pStatus = await Permission.photos.status;
    } else {
      pStatus = await Permission.storage.status;
    }
    if (Platform.isAndroid && pStatus == PermissionStatus.denied) {
      if ((appContext.storage.getString('PermissionPhoto') ?? "") != '1') {
        var iscuees = await PermissionHelper.showTipsPermissionDialog(
            context,
            S().permission_tips,
            getPermissionTips('WRITE_EXTERNAL_STORAGE') ??
                S().NSPhotoLibraryUsageDescription);
        if (iscuees != true) {
          return false;
        }
      }
    }

    PermissionStatus status;
    if (Platform.isIOS ||
        (Platform.isAndroid &&
            (int.tryParse(deviceData?.version.release ??'13') ?? 0) >= 13)) {
      status = await Permission.photos.request();
    } else {
      status = await Permission.storage.request();
    }

    var preDenied = appContext.storage.getString('PermissionPhoto') ?? "";
    // 从未申请过权限, 申请权限
    if (status.isGranted || status.isLimited) {
      print('undetermined & request permission && isGranted');
      return true;
    } else {
      if (preDenied == '1') {
        showPermissionDialog(
            context, S.of(context).privacy_setting_photo_toast);
      } else {
        appContext.storage.setString('PermissionPhoto', '1');
      }
      return false;
    }
  }

  // static Future<bool> checkAddPhotosPermission(BuildContext context) async {
  //   // Permission.phone
  //   PermissionStatus pStatus = await (Platform.isIOS
  //       ? Permission.photosAddOnly.status
  //       : Permission.storage.status);
  //   // DLog(camera);
  //   if (Platform.isAndroid && pStatus == PermissionStatus.denied) {
  //     if ((appContext.storage.getString('PermissionPhoto') ?? "") != '1') {
  //       var iscuees = await PermissionHelper.showTipsPermissionDialog(
  //           context,
  //           S().permission_tips,
  //           getPermissionTips('WRITE_EXTERNAL_STORAGE') ??
  //               S().NSPhotoLibraryUsageDescription);
  //       if (iscuees != true) {
  //         return false;
  //       }
  //     }
  //   }
  //   PermissionStatus status = await (Platform.isIOS
  //       ? Permission.photosAddOnly.request()
  //       : Permission.storage.request());
  //   var preDenied = Platform.isAndroid
  //       ? appContext.storage.getString('PermissionPhoto') ?? ""
  //       : (appContext.storage.getString('PermissionAddPhoto') ?? "");
  //   // 从未申请过权限, 申请权限
  //   if (status.isGranted || status.isLimited) {
  //     print('undetermined & request permission && isGranted');
  //     return true;
  //   } else {
  //     if (preDenied == '1') {
  //       showPermissionDialog(
  //           context, S.of(context).privacy_setting_photo_toast);
  //     } else {
  //       if (Platform.isAndroid) {
  //         appContext.storage.setString('PermissionPhoto', '1');
  //       } else {
  //         appContext.storage.setString('PermissionAddPhoto', '1');
  //       }
  //     }
  //     return false;
  //   }
  // }

  static Future<bool> checkLocationPermission(BuildContext context) async {
    PermissionStatus pStatus = await Permission.locationWhenInUse.status;
    // DLog(camera);
    if (Platform.isAndroid && pStatus == PermissionStatus.denied) {
      if ((appContext.storage.getString('PermissionLocation') ?? "") != '1') {
        var iscuees = await PermissionHelper.showTipsPermissionDialog(
            context,
            S().permission_tips,
            getPermissionTips('ACCESS_COARSE_LOCATION') ??
                S().NSLocationWhenInUseUsageDescription);
        if (iscuees != true) {
          return false;
        }
      }
    }
    PermissionStatus status = await Permission.locationWhenInUse.request();
    var preDenied = appContext.storage.getString('PermissionLocation') ?? "";
    // 从未申请过权限, 申请权限
    if (status.isGranted || status.isLimited) {
      print('undetermined & request permission && isGranted');
      return true;
    } else {
      if (preDenied == '1') {
        showPermissionDialog(
            context, S.of(context).privacy_setting_location_toast);
      } else {
        appContext.storage.setString('PermissionLocation', '1');
      }
      return false;
    }
  }

  static Future showTipsPermissionDialog(
      BuildContext context, String titleText, String hintText) {
    return showCommonDialog(
        context,
        DialogEntity(
            titleText,
            Text(
              hintText,
              style: TextStyle(
                color: ThemeColor.colorBlack100,
                fontSize: 16,
                fontWeight: FontWeight.w300,
              ),
            ), () {
          Navigator.of(context).pop(false);
        }, () {
          Navigator.of(context).pop(true);
        }, okText: S.of(context).ok, cancelText: S.of(context).cancel));
  }

  static showPermissionDialog(BuildContext context, String hintText) {
    showCommonDialog(
        context,
        DialogEntity(
            '',
            Text(
              hintText,
              style: TextStyle(
                color: ThemeColor.colorBlack100,
                fontSize: 16,
                fontWeight: FontWeight.w300,
              ),
            ), () {
          Navigator.of(context).pop(true);
        }, () {
          Navigator.of(context).pop(true);
          openAppSettings();
        }, okText: S.of(context).ok, cancelText: S.of(context).cancel));
  }
//   return showCupertinoDialog<bool>(
//       context: context,
//       builder: (context) {
//         return CupertinoAlertDialog(
//           content: Container(
//             padding: EdgeInsets.only(top: 12),
//             child: Text(hintText),
//           ),
//           actions: <Widget>[
//             TextButton(
//               child: Text(
//                 S.of(context).ok,
//                 style: TextStyle(
//                   color: ThemeColor.primaryColor,
//                 ),
//               ),
//               onPressed: () {
//                 //关闭对话框并返回true
//                 Navigator.of(context).pop(true);
//                 openAppSettings();
//               },
//             ),
//             TextButton(
//               child: Text(
//                 S.of(context).cancel,
//                 style: TextStyle(
//                   color: ThemeColor.primaryColor,
//                 ),
//               ),
//               onPressed: () {
//                 //关闭对话框并返回true
//                 Navigator.of(context).pop(true);
//               },
//             ),
//           ],
//         );
//       });
// }
}
